#include "basicwindow.h"
//#include "ui_basicwindow.h"
#include "CommonUtils.h"
#include "NotifyManager.h"
#include <QFile>
#include <QStyleOption>
#include <QPainter>
#include <QApplication>
#include <QScreen>

BasicWindow::BasicWindow(QWidget *parent) :
    QDialog(parent)
//    ui(new Ui::BasicWindow)
{
//    ui->setupUi(this);
    m_colorBackGround = CommonUtils::getDefaultSkinColor();//从配置文件tradeprintinfo.ini获取颜色
    setWindowFlags(Qt::FramelessWindowHint);			//没有边框
    setAttribute(Qt::WA_TranslucentBackground, true);	//透明效果
    connect(NotifyManager::getInstance(), SIGNAL(signalSkinChanged(const QColor&)), this, SLOT(onSignalSkinChanged(const QColor&)));
}

BasicWindow::~BasicWindow()
{
//    delete ui;
}


void BasicWindow::onSignalSkinChanged(const QColor& color)
{
    m_colorBackGround = color;
    loadStyleSheet(m_styleName);
}

//设置标题
void BasicWindow::setTitleBarTitle(const QString& title, const QString& icon)
{
    m_titleBar->setTitleIcon(icon);
    m_titleBar->setTitleContent(title);
}
//初始化标题栏
void BasicWindow::initTitleBar(ButtonType buttontype)
{
    m_titleBar = new TitleBar(this);
    m_titleBar->setButtonType(buttontype);
    m_titleBar->move(0, 0);

    //标题栏最小化按钮触发
    connect(m_titleBar, SIGNAL(signalButtonMinClicked()), this, SLOT(onButtonMinClicked()));
    //标题栏最大化还原按钮触发
    connect(m_titleBar, SIGNAL(signalButtonRestoreClicked()), this, SLOT(onButtonRestoreClicked()));
    //标题栏最大化按钮触发
    connect(m_titleBar, SIGNAL(signalButtonMaxClicked()), this, SLOT(onButtonMaxClicked()));
    //标题栏关闭按钮触发
    connect(m_titleBar, SIGNAL(signalButtonCloseClicked()), this, SLOT(onButtonCloseClicked()));

}
//加载样式表
void BasicWindow::loadStyleSheet(const QString& sheetName)
{
    m_styleName = sheetName;
    QFile file(":/Resources/QSS/" + sheetName + ".css");
    file.open(QFile::ReadOnly);

    if (file.isOpen())
    {
        setStyleSheet("");
        QString qsstyleSheet = QLatin1String(file.readAll());

        //获取用户当前的皮肤RGB值
        QString r = QString::number(m_colorBackGround.red());
        QString g = QString::number(m_colorBackGround.green());
        QString b = QString::number(m_colorBackGround.blue());

        qsstyleSheet += QString("QWidget[titleskin=true]\
                                {background-color:rgb(%1,%2,%3);\
                                border-top-left-radius:4px;}\
                                QWidget[bottomskin=true]\
                                {border-top:1px solid rgba(%1,%2,%3,100);\
                                background-color:rgba(%1,%2,%3,50);\
                                border-bottom-left-radius:4px;\
                                border-bottom-right-radius:4px;}")
                                .arg(r).arg(g).arg(b);//
        setStyleSheet(qsstyleSheet);
    }

    file.close();
}
//初始化背景
void BasicWindow::initBackGroundColor()
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
//子类化部件时，需要重写绘图事件来设置背景图
void BasicWindow::paintEvent(QPaintEvent* event)
{
    initBackGroundColor();
    QDialog::paintEvent(event);
}
//头像转圆头像
QPixmap BasicWindow::getRoundImage(const QPixmap& src, QPixmap& mask, QSize maskSize)
{
    if (maskSize == QSize(0, 0))
    {
        maskSize = mask.size();
    }
    else
    {
        mask = mask.scaled(maskSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);//缩放（缩放尺寸，尽可能大的进行缩放，进行平滑的方式缩放）
    }

    //保存转换后的图像
    QImage resultImage(maskSize, QImage::Format_ARGB32_Premultiplied);
    QPainter painter(&resultImage);
    painter.setCompositionMode(QPainter::CompositionMode_Source);//设置图片叠加模式-输出原图像
    painter.fillRect(resultImage.rect(), Qt::transparent);//填充一个矩形，（大小为图片的大小，透明的）
    painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
    painter.drawPixmap(0, 0, mask);
    painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
    painter.drawPixmap(0, 0, src.scaled(maskSize,Qt::KeepAspectRatio, Qt::SmoothTransformation));
    painter.end();
    return QPixmap::fromImage(resultImage);
}

void BasicWindow::onShowClose(bool)
{
    close();
}
void BasicWindow::onShowMin(bool)
{
    showMinimized();
}

void BasicWindow::onShowHide(bool)
{
    hide();
}

void BasicWindow::onShowNormal(bool)
{
    show();
    activateWindow();
}

void BasicWindow::onShowQuit(bool)
{
    QApplication::quit();
}
//鼠标移动事件
void BasicWindow::mouseMoveEvent(QMouseEvent *e)
{
    if (m_mousePressed && (e->buttons() && Qt::LeftButton))
    {
        //e->globalPosition().toPoint()事件发生时的全局坐标，相对于屏幕左上角（0,0）

//        move(e->globalPosition().toPoint() - m_mousePoint);//qt5.10之后的表示方法
        move(e->globalPos() - m_mousePoint);//qt5.10之前的表示方法

        e->accept();
    }
}
//鼠标点击事件
void BasicWindow::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton)
    {

        m_mousePressed = true;
        //pos()事件发生时，相对于窗口左上角（0,0）的偏移
//        m_mousePoint = e->globalPosition().toPoint() - pos();//qt5.10之后的表示方法
        m_mousePoint = e->globalPos() - pos();//qt5.10之前的表示方法
        e->accept();/*表示接受事件，告诉 Qt 事件已经被处理，不再传播到其他处理器（如父窗口等）。
                    如果不调用 accept()，事件可能会继续传递，导致默认的行为执行。
                    可能导致的后果就是点击界面之后，程序直接结束*/
    }
}
//鼠标松开事件
void BasicWindow::mouseReleaseEvent(QMouseEvent*)
{
    m_mousePressed = false;

}
//皮肤改变

void BasicWindow::onButtonMinClicked()
{
    /*检查当前窗口是否为工具窗口
        如果是工具窗口，则直接隐藏
        如果不是工具窗口，则最小化该窗口*/
    if (Qt::Tool == (windowFlags() & Qt::Tool))
    {
        hide();
    }
    else
    {
        showMinimized();
    }
}
void BasicWindow::onButtonRestoreClicked()
{
    QPoint windowPos;
    QSize windowSize;
    m_titleBar->getRestoreInfo(windowPos, windowSize);
    setGeometry(QRect(windowPos, windowSize));

}
void BasicWindow::onButtonMaxClicked()
{
    m_titleBar->saveRestoreInfo(pos(), QSize(width(), height()));
    //qt6用法，QScreen
    QScreen* screen = QGuiApplication::primaryScreen();
    QRect desktopRect = screen->availableGeometry();
    //qt5用法，需要头文件#include <QDesktopWidget>
    //QRect desktopRect = QApplication::desktop().availableGeometry();
    QRect factRect = QRect(desktopRect.x() - 3, desktopRect.y() - 3,
        desktopRect.width() + 6, desktopRect.height() + 6);
    setGeometry(factRect);

}
void BasicWindow::onButtonCloseClicked()
{
    close();
}
